package com.wrs.wrsfcmpush.service

import android.os.Build
import android.telecom.Connection
import android.telecom.ConnectionRequest
import android.telecom.ConnectionService
import android.telecom.PhoneAccountHandle
import android.telecom.TelecomManager
import android.telecom.TelecomManager.PRESENTATION_ALLOWED
import android.util.Log
import androidx.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.M)
class MyConnectionService : ConnectionService()  {
    var tag = "voip MyConnectionService"

    override fun onCreateOutgoingConnection(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?): Connection {
        Log.i(tag, "onCreateOutgoingConnection")
        // 创建一个新的通话连接
        return this.getConnection(connectionManagerPhoneAccount, request)
    }

    override fun onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?) {
        super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request)
        Log.i(tag, "create outgoing call failed")
    }

    override fun onCreateIncomingConnection(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?): Connection {

        Log.i(tag, "onCreateIncomingConnection")
        return this.getConnection(connectionManagerPhoneAccount, request)
    }

     fun getConnection(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?): Connection {


        val conn = CallConnection(applicationContext)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            conn.connectionProperties = Connection.PROPERTY_SELF_MANAGED
        }
        conn.setCallerDisplayName("test call", TelecomManager.PRESENTATION_ALLOWED)
        conn.setAddress(request!!.address, PRESENTATION_ALLOWED)
//      简单的通话功能，hold能力一般不需要进行支持,
//      测试加上hold能力时，新加入的系统来电接通时，会提示正在通话中，请不要挂机。
      conn.setConnectionCapabilities(Connection.CAPABILITY_HOLD or Connection.CAPABILITY_SUPPORT_HOLD);
         //设置这个属性才会调用Connection的onShowIncomingCallUi方法
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
             conn.setConnectionProperties(Connection.PROPERTY_SELF_MANAGED)
         };
         conn.setAudioModeIsVoip(true);

        conn.setInitializing()
        conn.setActive()

        return conn
    }

    override fun onCreateIncomingConnectionFailed(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?) {
        super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request)
        Log.i(tag, "create outgoing call failed ")
    }
}